package com.pds.web.category.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.core.domain.model.LoginUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.web.category.entity.PdsCategory;
import com.pds.web.category.entity.PdsCategoryStandard;
import com.pds.web.category.mapper.PdsCategoryMapper;
import com.pds.web.category.mapper.PdsCategoryStandardMapper;
import com.pds.web.category.service.PdsCategoryService;
import com.pds.web.category.vo.CategoryStandardVO;
import com.pds.web.category.vo.CategoryVO;
import com.pds.web.category.vo.StandardVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 检测项目类别表
 *
 * @author srf sunlightcs@gmail.com
 * @since 1.0.0 2024-02-29
 */
@Service("pdsCategoryService")
public class PdsCategoryServiceImpl extends ServiceImpl<PdsCategoryMapper, PdsCategory> implements PdsCategoryService {
    @Resource
    private PdsCategoryMapper pdsCategoryMapper;
    @Resource
    private PdsCategoryStandardMapper pdsCategoryStandardMapper;

    @Override
    public Map selectList(String status, String organizationId) {
        PdsCategory pdsCategory = new PdsCategory();
        if(StringUtils.isNotEmpty(status)){
            pdsCategory.setStatus(status);
        }
        List<CategoryStandardVO> categoryList = pdsCategoryMapper.selectList(pdsCategory);
        List<CategoryStandardVO> firstList = makeCategoryTree(categoryList);
        Map result = new HashMap(2);
        result.put("categoryList",firstList);
        //查询企业的检测范围
        if(StringUtils.isNotEmpty(organizationId)) {
            String categoryIds = pdsCategoryMapper.selectListByOrganizationId(organizationId);
            result.put("categoryIds",categoryIds);
        }
        return result;
    }

    /**
     * 构建树结构
     * @param categoryList
     * @return
     */
    private List<CategoryStandardVO> makeCategoryTree(List<CategoryStandardVO> categoryList) {
        List<CategoryStandardVO> firstList = new ArrayList<>();
        if(!Objects.isNull(categoryList) && !categoryList.isEmpty()){
            firstList = categoryList.stream().filter(c -> c.getLevel().intValue() == 1).collect(Collectors.toList());
            List<CategoryStandardVO> secondList = categoryList.stream().filter(c -> c.getLevel().intValue() == 2).collect(Collectors.toList());
            List<CategoryStandardVO> threeList = categoryList.stream().filter(c -> c.getLevel().intValue() == 3).collect(Collectors.toList());
            for (CategoryStandardVO category : secondList) {
                List<CategoryStandardVO> children = threeList.stream().filter(s -> s.getParentId().intValue() == category.getId()).collect(Collectors.toList());
                category.setChildren(children);
            }
            for (CategoryStandardVO category : firstList) {
                List<CategoryStandardVO> children = secondList.stream().filter(s -> s.getParentId().intValue() == category.getId()).collect(Collectors.toList());
                category.setChildren(children);
            }

        }
        return firstList;
    }

    @Override
    public Integer selectListCount(PdsCategory pdsCategory) {
        QueryWrapper<PdsCategory> wrapper = new QueryWrapper<>();
        String name = pdsCategory.getName();
        String status = pdsCategory.getStatus();
        if(!Objects.isNull(name) && !name.isEmpty()){
            wrapper.like("name",name);
        }
        if(!Objects.isNull(status) && !status.isEmpty()){
            wrapper.eq("status",status);
        }
        wrapper.eq("level","1");
        return pdsCategoryMapper.selectCount(wrapper);
    }

    @Override
    public PdsCategory queryById(Long id) {
        return pdsCategoryMapper.selectById(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public PdsCategory insert(PdsCategory pdsCategory) {
        Date date = DateUtils.parseDate(DateUtils.getTime());
        pdsCategory.setStatus("1");
        pdsCategory.setCreateTime(date);
        pdsCategoryMapper.insert(pdsCategory);
        return pdsCategory;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public Boolean update(PdsCategory pdsCategory) {
        Date date = DateUtils.parseDate(DateUtils.getTime());
        pdsCategory.setUpdateTime(date);
        return pdsCategoryMapper.updateById(pdsCategory) > 0;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public Object deleteById(Long id) {
        QueryWrapper<PdsCategoryStandard> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",id);
        Integer count = pdsCategoryStandardMapper.selectCount(wrapper);
        if(count > 0){
            return "该项目类别下包含项目标准，不允许删除！";
        }
        return pdsCategoryMapper.deleteById(id) > 0;
    }

    /**
     * 查询当前登录用户检测机构的检测因子
     * @return
     */
    @Override
    public List<CategoryStandardVO> getOrganizationCategory() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long organizationId = user.getDept().getOrganizationId();
        //查询机构检测因子
        List<CategoryStandardVO> categoryList = pdsCategoryMapper.getOrganizationCategory(organizationId);
        if(categoryList==null || categoryList.size()==0){
            return null;
        }
        //查询所有父级分类(2级)
        Set<Long> ids = new HashSet<>();
        categoryList.forEach(c -> ids.add(c.getParentId()));
        PdsCategory pdsCategory = new PdsCategory();
        pdsCategory.setIds(ids);
        List<CategoryStandardVO> secondList = pdsCategoryMapper.selectList(pdsCategory);
        ids.clear();
        //查询所有父级分类(3级)
        secondList.forEach(c -> ids.add(c.getParentId()));
        pdsCategory = new PdsCategory();
        pdsCategory.setIds(ids);
        List<CategoryStandardVO> firstList = pdsCategoryMapper.selectList(pdsCategory);
        categoryList.addAll(secondList);
        categoryList.addAll(firstList);
        //构造树结构
        return makeCategoryTree(categoryList);
    }
}
